/**
 * 
 */
package org.t2.backstage.module.mail.service;

import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.banish.sql.core.util.QuerySet;
import org.gaming.backstage.PageData;
import org.gaming.ruler.schedule.LoopingTask;
import org.gaming.service.advice.ResponseResult;
import org.gaming.service.service.AbstractService;
import org.gaming.tool.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.t2.backstage.module.gameserver.model.GameServer;
import org.t2.backstage.module.gameserver.service.GameServerService;
import org.t2.backstage.module.mail.model.MailSystem;
import org.t2.backstage.module.mail.model.MailSystemResult;
import org.t2.backstage.util.T2HttpUtil;

import sh.t2.share.apiutil.GameApi;
import sh.t2.share.module.mail.MailApiProtocol.MailSysDeleteRequest;
import sh.t2.share.module.mail.MailApiProtocol.MailSysDeleteResponse;
import sh.t2.share.module.mail.MailApiProtocol.MailToGameRequest;
import sh.t2.share.module.mail.MailApiProtocol.MailToGameResponse;

/**
 * @author YY
 *
 */
@Service
public class MailSystemService extends AbstractService<MailSystem> {

	@Autowired
	private GameServerService gameServerService;
	@Autowired
	private MailSystemResultService mailSystemResultService;
	
	private Queue<MailSystem> sendingQueue = new ConcurrentLinkedQueue<>();
	
	
	public MailSystem getEntity(long id) {
		return this.repository().getByKeys(id);
	}
	
	public PageData<MailSystem> query(QuerySet querySet) {
		List<MailSystem> list = this.repository().getBaseDao().queryListWhere(querySet.getWhere(), querySet.getParams());
		
		PageData<MailSystem> pageData = new PageData<>();
		pageData.setCount(this.repository().getBaseDao().countWhere(querySet.getCountWhere(), querySet.getCountParams()));
		pageData.setData(list);
		return pageData;
	}
	
	public void updateAll(List<MailSystem> mails) {
		this.repository().updateAll(mails);
	}
	
	public void addToSending(MailSystem mail) {
		sendingQueue.add(mail);
	}
	
	@LoopingTask(name = "MailSystemService", spaceTime = DateTimeUtil.ONE_SECOND_MILLIS, execGroup = 3)
	private void runInSchedule() {
		MailSystem mail = sendingQueue.poll();
		if(mail == null) {
			return;
		}
		if(mail.getStatus() == 1) {
			tellSendMail(mail);
		} else if(mail.getStatus() == 3) {
			tellDeleteMail(mail);
		}
	}
	
	/**
	 * 通知游戏服发送邮件
	 * @param mail
	 */
	public void tellSendMail(MailSystem mail) {
		MailToGameRequest request = new MailToGameRequest();
		request.id = mail.getId();
		request.title = mail.getTitle();
		request.content = mail.getContent();
		request.rewards = mail.getRewards();
		request.type = mail.getType();
		request.playerIds = mail.getPids();
		
		try {
			logger.info("正在将邮件{}发向各服务器", mail.getId());
			for(int serverUid : mail.getServerUids()) {
				if(mail.getSendServerUids().contains(serverUid)) {
					continue;
				}
				
				MailSystemResult result = new MailSystemResult();
				result.setMailId(mail.getId());
				result.setServerUid(serverUid);
				result.setTypeText("发送邮件");
				
				GameServer gameServer = gameServerService.getEntity(0, serverUid);
				if(gameServer == null) {
					result.setMessage("通过唯一ID" + serverUid + "未找到服务器");
					result.setStatus(2);
				} else {
					result.setServerId(gameServer.getServerId());
					result.setServerName(gameServer.getName());
					
					ResponseResult<MailToGameResponse> serverResponse = T2HttpUtil.jsonPost(gameServer, GameApi.sendMailSystem, request, MailToGameResponse.class);
					if(serverResponse == null) {
						result.setStatus(2);
						result.setMessage("未收到游戏服" + serverUid + "的响应");
					} else {
						result.setMessage(serverResponse.getMessage());
						if(serverResponse.getCode() == 0) {
							result.setStatus(1);
							mail.getSendServerUids().add(serverUid);
						} else {
							result.setStatus(2);
						}
					}
				}
				mailSystemResultService.insert(result);
			}
		} finally {
			this.update(mail);
		}
	}
	
	/**
	 * 通知游戏服删除邮件
	 * @param mail
	 */
	public void tellDeleteMail(MailSystem mail) {
		try {
			for(int serverUid : mail.getServerUids()) {
				if(mail.getDeleteServerUids().contains(serverUid)) {
					continue;
				}
				
				MailSystemResult result = new MailSystemResult();
				result.setMailId(mail.getId());
				result.setServerUid(serverUid);
				result.setTypeText("删除邮件");
				
				GameServer gameServer = gameServerService.getEntity(0, serverUid);
				if(gameServer == null) {
					result.setMessage("通过唯一ID" + serverUid + "未找到服务器");
				} else {
					result.setServerId(gameServer.getServerId());
					result.setServerName(gameServer.getName());
					
					MailSysDeleteRequest request = new MailSysDeleteRequest();
					request.mailSystemId = mail.getId();
					ResponseResult<MailSysDeleteResponse> serverResponse = T2HttpUtil.jsonPost(gameServer, GameApi.deleteMailSystem, request, MailSysDeleteResponse.class);
					if(serverResponse == null) {
						result.setMessage("请求服务器返回null");
					} else {
						result.setMessage(serverResponse.getMessage());
						if(serverResponse.getCode() == 0) {
							//发送成功
							mail.getDeleteServerUids().add(serverUid);
						}
					}
					
				}
				mailSystemResultService.insert(result);
			}
		} finally {
			this.update(mail);
		}
	}

	@Override
	public void mergeServer(int mergeDbZoneId) {
		//不用实现
	}
	
}
